package com.apache.gateway.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;

/**
 * @description: 自定义过滤器
 * @author: Hou Dayu
 * @date: Created in 2020/4/8
 */
public class LogMsgLevelFilter extends AbstractMatcherFilter<ILoggingEvent> {

    Level level;

    public LogMsgLevelFilter() {
    }

    /**
     * 返回值为DENY时，日志事件直接丢弃这条日志，不会再传递给剩下的过滤器。返回值为NEUTRAL时，则传递给下面的过滤器。返回值为ACCEPT时，日志事件立即处理这条日志，跳过调用其它过滤器
     */
    public FilterReply decide(ILoggingEvent event) {
        String msg = event.getMessage().trim();
        if(msg.startsWith("traceId = ") || msg.startsWith("processingStage = ") || msg.startsWith("exception = ")){
            if (!this.isStarted()) {
                return FilterReply.NEUTRAL;
            } else {
                return event.getLevel().equals(this.level) ? this.onMatch : this.onMismatch;
            }
        } else {
            return FilterReply.DENY;
        }
    }

    public void setLevel(Level level) {
        this.level = level;
    }

    public void start() {
        if (this.level != null) {
            super.start();
        }

    }
}
